package com.cms.recursoshumanos.activity.acceso;

import com.example.frontendrecursoshumanos.R;
import com.cms.recursoshumanos.activity.main.MainRecursosHumanosActivity;
import com.cms.recursoshumanos.cache.UserInfoCache;
import com.cms.recursoshumanos.constant.Constant;
import com.cms.recursoshumanos.handler.LoginActivityHandler;
import com.cms.recursoshumanos.handler.MyUserDetailActivyHandler;
import com.cms.recursoshumanos.object.Usuario;
import com.cms.recursoshumanos.utilities.Tool;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Intent;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends MainRecursosHumanosActivity 
{

	protected static LoginAsync mLoginAsyncTask;
	protected static AllUserDetailsAsync allUserDetailsAsyncTask;
	
	private static EditText usernameField;
	private static EditText passwordField;
	
	private ProgressDialog dialog;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setComponents();
        
        try
        {
        	if(getIntent().getExtras().size() == 0);
        }
        catch (Exception ee)
        {
        	if (Tool.getInstance().isInfoSavedInDeviceFromUser())
	        {
	        	Tool.getInstance().getUserInfoShared();
	        	usernameField.setText(UserInfoCache.getInstance().getUsuario().getNombre_Usuario());
	        	makeLogin(UserInfoCache.getInstance().getUsuario().getNombre_Usuario(),
	        				UserInfoCache.getInstance().getUsuario().getPassword());
	        }
        }  
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void setComponents()
    {
    	usernameField = (EditText) findViewById(R.id.etUsername);
		passwordField = (EditText) findViewById(R.id.etPassword);
    }
    public void showPass(View v)
    {
		
		if (passwordField.getTransformationMethod() == null)
			passwordField.setTransformationMethod(new PasswordTransformationMethod());
		else
			passwordField.setTransformationMethod(null);
	}
    public boolean verificar_campos_login()
    {
    	if (usernameField.getText().toString().equals(""))
		{
			Toast.makeText(getAppContext(),"Introduzca su nombre de usuario"
					, Toast.LENGTH_LONG).show();
			return false;
		}
		else if (passwordField.getText().toString().equals(""))
		{

			Toast.makeText(getAppContext(),"Introduzca su contraseña"
					, Toast.LENGTH_LONG).show();
			return false;
		}
		else
		{
			return true;
		}
    }
    public void onLoginClick(View view)
    {
		if (verificar_campos_login())
		{
			makeLogin(usernameField.getText().toString(),
						passwordField.getText().toString());
		}
	}
	public void onLostClick(View view)
    {
		goPaginaLostDecision();
	}
	
    protected void makeLogin(String username, String password)
    {
		if (isOnline())
		{
	    	mLoginAsyncTask = new LoginAsync(username,password);
			mLoginAsyncTask.execute();
		}
	}
    protected void getAllUserInfo(Usuario elUsuario)
    {
    	if (isOnline())
		{
    		allUserDetailsAsyncTask = new AllUserDetailsAsync(elUsuario);
    		allUserDetailsAsyncTask.execute();
		}
	}
  
    public void goPaginaLostDecision()
    {
    	Intent	intent = new Intent(LoginActivity.this, LostDecisionActivity.class);
		startActivity(intent);
    }
    private class AllUserDetailsAsync extends AsyncTask<String, Void, String>
	{

		private Usuario elUsuario;
    	
		public AllUserDetailsAsync(Usuario elUsuario)
		{
			this.elUsuario = elUsuario;
		}
		
		@SuppressWarnings("deprecation")
		@Override
		protected void onPreExecute()
		{
			showDialog(0);
			
			dialog = ProgressDialog.show(LoginActivity.this, "Espere","Obteniendo Informacion Personal del Usuario",true );
		}

		@Override
		protected String doInBackground(String... arg0) 
		{
			
			MyUserDetailActivyHandler handler = new MyUserDetailActivyHandler();
			String result = handler.MyUserDetail(this.elUsuario.getNombre_Usuario(), 
													this.elUsuario.getPassword());
			return result;
		}
		
		@Override
		public void onPostExecute(String  result)
		{
			
			String str_result = result;
			
			if (str_result.equals(Constant.CODE_OK))
			{ 
				Tool.getInstance().saveUserInfoShared(9,UserInfoCache.getInstance());
				goPaginaPrincipal(LoginActivity.this);
			}
			else 
			{
				Tool.getInstance().showMessage(str_result);
			}
			dialog.cancel();
			this.cancel(true);
			
		}
		
	}
    
    private class LoginAsync extends AsyncTask<String, Void, String>
	{

		private String username;
		private String password;
		public LoginAsync(String username,String password)
		{
			this.username = username;
			this.password = password;
		}
		@SuppressWarnings("deprecation")
		@Override
		protected void onPreExecute()
		{
			showDialog(0);
			
			dialog = ProgressDialog.show(LoginActivity.this, "Espere","Autentificando al Usuario...",true );
		}

		@Override
		protected String doInBackground(String... arg0) 
		{

			LoginActivityHandler handler = new LoginActivityHandler();
			String result = handler.LoginSistema(username, password);
			return result;
		}
		
		@Override
		public void onPostExecute(String  result)
		{
			
			String str_result = result;
			dialog.cancel();
			if (str_result.equals(Constant.CODE_OK))
			{ 
				
				/*if (Tool.getInstance().verifyIsUserIsTheSame(username))
				{
					Tool.getInstance().getUserInfoShared(getAppContext());
					goPaginaPrincipal();
				}*/
				/*else
				{*/
					//Tool.getInstance().deleteUserShared(MainRecursosHumanosActivity.getAppContext());
						
					UserInfoCache.getInstance().setUsuario(new Usuario(0, username, password));
					getAllUserInfo(UserInfoCache.getInstance().getUsuario());
				/*}*/

			}
			else 
			{
				Tool.getInstance().showMessage(str_result);
			}
			
			this.cancel(true);
			
		}
		
	}
    
}
